package com.dili.dd.gpi.service.impl;

import com.dili.dd.gpi.domain.SiteApp;
import com.dili.dd.gpi.domain.SiteAppExample;
import com.dili.dd.gpi.enums.APPType;
import com.dili.dd.gpi.mapper.SiteAppMapper;
import com.dili.dd.gpi.service.SiteAppService;
import com.dili.dd.gpi.util.spring.DataSourceLookupKey;
import com.dili.dd.gpi.util.spring.RequireDataSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by zhaoYuan on 2015/10/19.
 */
@Service
public class SiteAppServiceImpl implements SiteAppService {

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Resource
    private SiteAppMapper siteAppMapper;

    @Override
    @RequireDataSource(key = DataSourceLookupKey.GPI_DATASOURCE)
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void addSiteApp(int siteId, String key, APPType appType) {
        SiteApp app = new SiteApp();
        app.setDeleted(false);
        app.setAppType(appType);
        app.setKey(key);
        app.setSiteId(siteId);
        siteAppMapper.insert(app);
    }

    @Override
    @RequireDataSource(key = DataSourceLookupKey.GPI_DATASOURCE)
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void batAddSiteApp(List<SiteApp> siteApps) {
        for (SiteApp app : siteApps) {
            app.setDeleted(false);
            siteAppMapper.insert(app);
        }
    }

    @Override
    @RequireDataSource(key = DataSourceLookupKey.GPI_DATASOURCE)
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void deletedSiteApp(int siteAppId) {
        SiteApp siteApp = siteAppMapper.selectByPrimaryKey(siteAppId);
        siteApp.setDeleted(true);
        siteAppMapper.updateByPrimaryKeySelective(siteApp);
    }

    @Override
    @RequireDataSource(key = DataSourceLookupKey.GPI_DATASOURCE)
    @Transactional(readOnly = false,propagation = Propagation.SUPPORTS)
    public List<SiteApp> findBySite(int siteId) {
        SiteAppExample example = new SiteAppExample();
        example.createCriteria().andSiteIdEqualTo(siteId).andDeletedEqualTo(false);
        return siteAppMapper.selectByExample(example);
    }
}
